import React from "react";
import { useHistory } from "react-router-dom";
import { connect } from "react-redux";

import { Form, Modal, message } from "antd";
import * as Reducer from "store/modify-password/reducer";
import * as Action from "store/modify-password/action";
import * as Api from "api/api";
import * as css from "./css/modify-password";

function ModifyPassword(props) {
  const { action, modifyPassword, app, form } = props;
  const { getFieldDecorator, validateFields } = form;
  let history = useHistory();

  function onInputChange(payload) {
    action.setInput(payload);
  }

  function toBack() {
    history.go(-1);
  }

  function doModify(e) {
    e.preventDefault();
    validateFields(async (err, values) => {
      if (!err) {
        const { input } = modifyPassword;
        const { password, oldPassword } = input;
        const { username } = app;

        const res = await Api.modifyPassword({
          username,
          oldPassword,
          password
        });

        if (res.status === 200) {
          Modal.success({
            content: "修改成功！",
            okText: "去登录",
            closable: false,
            keyboard: false,
            maskClosable: false,
            onOk: () => {
              history.push("/login");
            }
          });
        } else {
          message.error("旧密码错误！");
        }
      }
    });
  }

  return (
    <css.ModifyPassword>
      <css.Main>
        <css.Title>修改密码</css.Title>
        <css.Form onSubmit={doModify}>
          <css.FormItem>
            {getFieldDecorator("input.oldPassword", {
              rules: [
                {
                  required: true,
                  message: "请输入密码"
                }
              ]
            })(
              <css.Input
                prefix={<css.Icon type="lock" />}
                placeholder="旧密码"
                type="password"
                value={modifyPassword.input.oldPassword}
                onChange={e => {
                  onInputChange({
                    [Reducer.form.oldPassword]: e.currentTarget.value
                  });
                }}
              ></css.Input>
            )}
          </css.FormItem>
          <css.FormItem>
            {getFieldDecorator("input.password", {
              rules: [
                {
                  required: true,
                  message: "请输入密码"
                }
              ]
            })(
              <css.Input
                prefix={<css.Icon type="lock" />}
                placeholder="密码"
                type="password"
                value={modifyPassword.input.password}
                onChange={e => {
                  onInputChange({
                    [Reducer.form.password]: e.currentTarget.value
                  });
                }}
              ></css.Input>
            )}
          </css.FormItem>
          <css.FormItem>
            {getFieldDecorator("input.password2", {
              rules: [
                {
                  required: true,
                  message: "请确认密码"
                },
                {
                  validator: async (rule, value, callback) => {
                    if (value && value !== modifyPassword.input.password) {
                      throw new Error();
                    }
                  },
                  message: "两次密码不一致"
                }
              ]
            })(
              <css.Input
                prefix={<css.Icon type="lock" />}
                placeholder="确认密码"
                type="password"
                value={modifyPassword.input.password2}
                onChange={e => {
                  onInputChange({
                    [Reducer.form.password2]: e.currentTarget.value
                  });
                }}
              ></css.Input>
            )}
          </css.FormItem>
          <css.Button type="primary" block htmlType="submit">
            确认修改
          </css.Button>
          <css.BackBlock>
            <css.BackText onClick={toBack}>返回</css.BackText>
          </css.BackBlock>
        </css.Form>
      </css.Main>
    </css.ModifyPassword>
  );
}

const FormModifyPassword = Form.create({ name: "register" })(ModifyPassword);

export default connect(
  state => {
    const { modifyPassword, app } = state;

    return {
      modifyPassword,
      app
    };
  },
  f => ({
    action: {
      setInput() {
        f(Action.setInput(...arguments));
      }
    }
  })
)(FormModifyPassword);
